import React, {useEffect, useState} from "react";
import {Button, Col, Form, Input, message, Modal, Row} from "antd";
import type {Result} from "@/types/result";
import positionApi from "@/api/positionApi.ts";
import {Position} from "@/types/resp/position";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";

interface PositionAddProps {
  visible: boolean;
  id: number;
  onClosePositionAdd: () => void;
}

const PositionAdd: React.FC<PositionAddProps> = ({visible, id, onClosePositionAdd}) => {

  const [form] = Form.useForm<Position>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    enterpriseName: [
      { required: true, message: '请输入企业名称' }
    ],
    positionName: [
      { required: true, message: '请输入岗位名称' }
    ],
  };

  let positionForm: Partial<Position> = {}

  const [title, setTitle] = useState('新增岗位信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑岗位信息')
      initPositionFormById(id)
    } else {
      setTitle('新增岗位信息')
      form.resetFields();
    }
  }, [visible]);

  const initPositionFormById = async (id: number) => {
    const resp: Result<Position> = await positionApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      positionForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let position2Save:Position = form.getFieldsValue()
      if (id) {
        position2Save = Object.assign(positionForm, position2Save)
      }
      const resp: Result<void> = await positionApi.save(position2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增岗位信息')
    form.resetFields();
  };
  
  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };

  const onBack = () => {
    onClosePositionAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onClosePositionAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="positionForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="enterpriseName" label="企业名称"  rules={rules.enterpriseName}>
              <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="positionName" label="岗位名称" rules={rules.positionName}>
              <Input maxLength={64} placeholder="请输入岗位名称"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={22}>
            <Form.Item name="responsibilities" label="岗位职责" labelCol={{span: 3}}>
              <Input.TextArea maxLength={65535} placeholder="请输入岗位职责" autoSize={{ minRows: 3, maxRows: 3 }}/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
    </Modal>
  )
}

export default PositionAdd;
